// import { RPCServer, ServerError } from "castle-rpc-server";
import { RPCServer, ServerError } from "castle-rpc-server/dist/index";
import { controller } from "./service";
import { RPC as CRPC } from 'castle-rpc'
class RPCService extends RPCServer {
    constructor() {
        super({})
    }
    async controller(path, data, rpc, ctx) {
        let p = path.split('/')
        if (p.length > 1) {
            if (p[0] == "" && p.length > 2) { p.shift() }
            ctx.control = {
                c: p[0],
                m: p.length == 1 ? 'index' : p[1],
            }
            // ctx.path = path;
        } else {
            throw 'ErrorPath'
        }
        ctx.req.body = data
        return await controller(ctx.control.c, ctx.control.m, Object.assign(ctx))
    }
    async send(content: CRPC | string | Buffer, ctx) {
        if ('object' == typeof content) {
            if (ctx.RPCEncoding != 'text' && content['encode'] instanceof Function) {
                content = content['encode']()
            } else {
                content = JSON.stringify(content)
            }
        }
        return ctx.websocket.send(content)
    }
    async sendTo(ID, Content, ctx) {
        try {
            if (this.clients[ID] && this.clients[ID].options && this.clients[ID].options.websocket) {
                return this.send(Content, this.clients[ID].options)
            } else {
                throw ServerError.NOT_ONLINE
            }
        } catch (error) {
            return false;
        }
    }
    get onlines() {
        return this.clients;
    }
}
export const RPC = new RPCService()